<?php

/**
 * 微信开发API
 * Class WxApi
 */
class WxApi
{

    /**
     * 获取AccessToken并缓存，失败返回false
     * @return bool|string
     */
    public static function getAccessToken()
    {
        require_once 'WxFunction.php';
        $data = WxFunction::cache('accessToken.json');
        if (is_array($data)){
            if (isset($data['access_token']) && isset($data['expire']) && $data['expire'] > time()){
                return $data['access_token'];
            }
        }
        // 获取accesstoken并缓存起来
        $api = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . WxConfig::APPID . '&secret=' . WxConfig::APPSECRET;
        $result = json_decode(WxFunction::curlGet($api), TRUE);
        if (is_array($result) && !empty($result['access_token'])){
            $data = array('access_token' => $result['access_token'], 'expire' => time() + 7000);
            WxFunction::cache('accessToken.json', $data);
            return $data['access_token'];
        }

        return FALSE;
    }

    /**
     * 获取JSapi票据并缓存，失败返回false
     * @return bool|string
     */
    public static function getJsApiTicket()
    {
        require_once 'WxFunction.php';
        $data = WxFunction::cache('jsApiTicket.json');
        if (is_array($data)){
            if (isset($data['ticket']) && isset($data['expire']) && $data['expire'] > time()){
                return $data['ticket'];
            }
        }
        // 获取JSapi票据并缓存起来
        $accessToken = self::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
        $result = json_decode(WxFunction::curlGet($url), TRUE);
        if (isset($result['errcode']) && $result['errcode'] == 0 && !empty($result['ticket'])){
            $data = array('ticket' => $result['ticket'], 'expire' => time() + 7000);
            WxFunction::cache('jsApiTicket.json', $data);
            return $data['ticket'];
        }

        return FALSE;
    }

    /**
     * 获取微信卡券票据并缓存，失败返回false
     * @return bool|string
     */
    public static function getCardTicket()
    {
        require_once 'WxFunction.php';
        $data = WxFunction::cache('cardTicket.json');
        if (is_array($data)){
            if (isset($data['ticket']) && isset($data['expire']) && $data['expire'] > time()){
                return $data['ticket'];
            }
        }
        // 获取微信卡券票据并缓存起来
        $accessToken = self::getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$accessToken}&type=wx_card";
        $result = json_decode(WxFunction::curlGet($url), TRUE);
        if (isset($result['errcode']) && $result['errcode'] == 0 && !empty($result['ticket'])){
            $data = array('ticket' => $result['ticket'], 'expire' => time() + 7000);
            WxFunction::cache('cardTicket.json', $data);
            return $data['ticket'];
        }

        return FALSE;
    }
}